package com.avengers.core.kit;

import com.google.gson.Gson;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * json 工具
 *
 * @author yu.wang
 * @since 2018-05-18 下午2:33
 */
public class JsonKit {

    private static final Gson gson = new Gson();

    public static <T> T fromJson(String str, Class<T> clazz, Class<?>... clazzs) {

        if (null != clazzs && clazzs.length > 0) {
            Type objectType = type(clazz, clazzs);

            return gson.fromJson(str, objectType);
        }
        return gson.fromJson(str, clazz);
    }

    public static String toJson(Object object) {

        if (null == object) {
            return null;
        }

        return com.jfinal.kit.JsonKit.toJson(object);
    }

    public static String toGson(Object object) {

        if (null == object) {
            return null;
        }

        return gson.toJson(object);
    }

    private static ParameterizedType type(final Class<?> raw, final Type... args) {

        return new ParameterizedType() {
            @Override
            public Type getRawType() {
                return raw;
            }

            @Override
            public Type[] getActualTypeArguments() {
                return args;
            }

            @Override
            public Type getOwnerType() {
                return null;
            }
        };
    }
}
